package cn.hfatec.base;

import cn.hfatec.constants.SysContant;
import cn.hfatec.web.WebContext;
import freemarker.ext.beans.BeansWrapper;
import freemarker.template.TemplateHashModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.beans.TypeMismatchException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 *
 * 封装异常统一处理
 *
 * @author: panwb
 *
 * Date: 14-2-27
 * Time: 下午5:00
 */
@Controller
public abstract class BaseAction {

    //日志对象
    protected Logger logger = LoggerFactory.getLogger(getClass());

    @ModelAttribute(value = SysContant.ABSOLUTE_CONTEXT_PATH)
    public String absoluteContextPath() {
        return (String) WebContext.getRequest().getAttribute(SysContant.ABSOLUTE_CONTEXT_PATH);
    }

    @ModelAttribute(value = "statics")
    public TemplateHashModel staticModel() {
        return BeansWrapper.getDefaultInstance().getStaticModels();
    }

    @ModelAttribute(value = "authentication")
    public Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

    /**
     *
     * 处理500异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(value = { ConversionNotSupportedException.class, HttpMessageNotWritableException.class})
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    public String handler500(Exception ex) {
        logger.error("{} : 500出错", WebContext.getRequest().getRequestURL(), ex);
        WebContext.getRequest().setAttribute("message", "sorry, something mistake");
        return "exception/500";
    }

    /**
     *
     * 处理400异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(value = { HttpMessageNotReadableException.class, MissingServletRequestParameterException.class,
            TypeMismatchException.class })
    @ResponseStatus(value = HttpStatus.BAD_REQUEST)
    public String handle400(Exception ex) {
        logger.error("{} : 400出错", WebContext.getRequest().getRequestURL(), ex);
        WebContext.getRequest().setAttribute("message", "sorry, something mistake");
        return "exception/400";
    }
}
